package com.vrv.app.cyberspace.common.utils;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @Description HttpClient工具类
 * @Author by sm
 * @Create 2017-08-14 17:56
 */
public class HttpClientUtil {
	private final static String UTF8 = "UTF-8";
	private final static String ISO88591 = "ISO-8859-1";
	private final static Integer COOKIEAGE = 7 * 24 * 3600;

	/**
	 * 处理get请求中文乱码的问题 即字符串ISO-8859-1转换为UTF-8
	 * 
	 * @param source
	 *            源字符串
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String handleISO2UTF8(String source) throws UnsupportedEncodingException {
		if (StringUtils.isEmpty(source)) {
			return "";
		}
		return new String(source.getBytes(ISO88591), UTF8);
	}

	/**
	 * post请求
	 * 
	 * @param url
	 *            请求路径
	 * @param params
	 *            参数
	 * @return
	 */
	public static String doPost(String url, Map<String, String> params) {
		HttpPost httpPost = new HttpPost(url);
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			if (params != null && params.size() != 0) {
				List<NameValuePair> nvps = new ArrayList<>();
				for (Entry<String, String> entry : params.entrySet()) {
					nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
				httpPost.setEntity(new UrlEncodedFormEntity(nvps, UTF8));
			}
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity, UTF8);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpPost.releaseConnection();
		}
		return null;
	}

	public static JSONObject doPost(String url, JSONObject json){
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		JSONObject response = null;
		try {
			StringEntity s = new StringEntity(json.toString(),"utf-8");
			s.setContentEncoding("UTF-8");
			s.setContentType("application/json");//发送json数据需要设置contentType
			httpPost.setEntity(s);
			HttpResponse res = httpClient.execute(httpPost);
			if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				String result = EntityUtils.toString(res.getEntity());// 返回json格式：
				response = JSONObject.parseObject(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpPost.releaseConnection();
		}
		return response;
	}

	/**
	 * get 请求
	 * 
	 * @param url
	 *            请求路径
	 * @return
	 */
	public static String doGet(String url) {
		HttpGet httpGet = new HttpGet(url);
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();

			HttpResponse response = httpClient.execute(httpGet);

			HttpEntity entity = response.getEntity();

			return EntityUtils.toString(entity, UTF8);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpGet.releaseConnection();
		}
		return null;
	}

	/**
	 * 从cookie中获取值
	 * 
	 * @param request
	 * @return
	 */
	public static String getValueInCookie(HttpServletRequest request, String name) {
		String userToken = "";
		for (Cookie cookie : request.getCookies()) {
			if (cookie.getName().equals(name)) {
				userToken = cookie.getValue();
				break;
			}
		}
		return userToken;
	}

	/**
	 * 创建cookie
	 *
	 * @param response
	 * @param name
	 *            名称
	 * @param value
	 *            值
	 */
	public static void makeCookie(HttpServletResponse response, String name, String value) {
		Cookie cookie = new Cookie(name, value);
		cookie.setMaxAge(COOKIEAGE);// 7 天过期
		response.addCookie(cookie);
	}
}
